package judger

import (
	"JudgeClient/idl"
	"encoding/json"
	"log"
	"os/exec"
	"strconv"
)

func Run(config idl.RunConfig) (idl.RunResult, error) {
	var args []string
	// parsing args
	args = append(args, "--max_cpu_time="+strconv.Itoa(config.MaxCpuTime))
	args = append(args, "--max_real_time="+strconv.Itoa(config.MaxRealTime))
	args = append(args, "--max_memory="+strconv.Itoa(config.MaxMemory))
	args = append(args, "--max_process_number="+strconv.Itoa(config.MaxProcessNumber))
	args = append(args, "--max_stack="+strconv.Itoa(config.MaxStack))
	args = append(args, "--max_output_size="+strconv.Itoa(config.MaxOutPutSize))
	args = append(args, "--exe_path="+config.ExePath)
	args = append(args, "--input_path="+config.InputPath)
	args = append(args, "--output_path="+config.OutputPath)
	args = append(args, "--error_path="+config.ErrorPath)
	args = append(args, "--log_path="+config.LogPath)
	// parsing list args
	for _, arg := range config.Args {
		args = append(args, "--args="+arg)
	}

	for _, env := range config.Env {
		args = append(args, "--env="+env)
	}

	args = append(args, "--seccomp_rule_name="+config.SecCompRuleName)
	if config.Uid >= 0 {
		args = append(args, "--uid="+strconv.Itoa(config.Uid))
	}
	if config.Gid >= 0 {
		args = append(args, "--gid="+strconv.Itoa(config.Gid))
	}

	cmd := exec.Command("/usr/lib/judger/libjudger.so", args...)

	output, err := cmd.Output()

	if err != nil {
		log.Println(err)
	}

	var runResult idl.RunResult

	if err := json.Unmarshal(output, &runResult); err != nil {
		log.Println(err)
	}

	return runResult, err
}
